package com.ambow.shop.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.ambow.shop.dao.ProductCategoryDao;
import com.ambow.shop.domain.ProductCategory;
import com.ambow.shop.util.JdbcUtils;

/**
 * 产品类别数据访问实现。
 * 
 * @author chunw
 *
 */
public class ProductCategoryDaoJdbcImpl implements ProductCategoryDao {

	@Override
	public int add(ProductCategory productCategory) throws SQLException {
		final String sql = "INSERT INTO productcategory(name, description) VALUES(?, ?)";
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		
		return runner.execute(sql, productCategory.getName(), productCategory.getDescription());
	}

	@Override
	public int delete(Integer id) throws SQLException {
		final String sql = "DELETE FROM productcategory WHERE id = ?";
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		return runner.execute(sql, id);
	}

	@Override
	public int update(ProductCategory productCategory) throws SQLException {
		final String sql = "UPDATE productcategory set name = ?, description = ? WHERE id = ?";
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		return runner.execute(sql, productCategory.getName(), productCategory.getDescription(),
				productCategory.getId());
	}

	@Override
	public ProductCategory get(Integer id) throws SQLException {
		final String sql = "SELECT id, name, description FROM productcategory WHERE id = ?";
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		return runner.query(sql, new BeanHandler<ProductCategory>(ProductCategory.class), id);
	}

	@Override
	public List<ProductCategory> list() throws SQLException {
		final String sql = "SELECT id, name, description FROM productcategory";
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		return runner.query(sql, new BeanListHandler<ProductCategory>(ProductCategory.class));
	}

}
